package com.self.reflect;

import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;

/**
 * 作者：tianjiayuan
 * 创建时间：2018-06-13 13:07
 * 类描述：
 * 修改人：
 * 修改时间：
 */
public class ClientProxy implements Subject{

    private Subject subject;

    public ClientProxy(Subject subject) {
        this.subject = subject;
    }

    @Override
    public String rent() {

        String url = subject.getClass().getName() + "&" + Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println(url);
        return new HttpInvoke().conect(url, 9000);
    }

    @Override
    public String hello(String str) {
        String url = subject.getClass().getName() + "&" + Thread.currentThread().getStackTrace()[1].getMethodName() + "&" + str;
        System.out.println(url);
        return new HttpInvoke().conect(url, 9000);
    }

    class HttpInvoke {
        public String conect(String url, int port) {
            try {
                url += "\r\n";
                Socket socket = new Socket("127.0.0.1", port);
                Writer writer = new OutputStreamWriter(socket.getOutputStream());
                writer.write(url);
                writer.write("eof");
                writer.flush();
                byte[] bytes = new byte[1024];
                StringBuilder builder = new StringBuilder();
                InputStream in = socket.getInputStream();
                while(in.read(bytes) != -1) {
                    builder.append(new String(bytes, "utf-8"));
                }
                in.close();
                writer.close();
                socket.close();
                System.out.println(builder.toString());
                return builder.toString();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

            }
            return "";
        }
    }

    public static void main(String[] args) {
        Subject subject = new RealSubject();
        ClientProxy proxy = new ClientProxy(subject);

        System.out.println(proxy.rent());
    }
}
